<?php
declare(encoding='UTF-8');
//namespace Slipstream\server;

class ss_cli_core {
	protected $settings=array();
	protected $config;
	private $command=array();
	
	public function __construct($config,$ss){
		$this->settngs=$ss;
		$this->config=$config;
		$this->loadCommands();
	}
	
	protected function loadCommands(){
		//print("Loading commands\n");
		$_glob=new GlobIterator(SS_ROOT_PATH."/ss/cli/command/ss_cli_command_*.php");
		foreach ($_glob as $file) {
			$_cmd=str_replace('ss_cli_command_','',$file->getBasename('.php'));
			$this->command[$_cmd]=null;
		    //print( "$filename size " . filesize($filename) . "\n");
		}
	}
	
	public function __call($func,$args){
		$_obj=$this->getCommand($func);
		if(count($args)>0){
			$_cmd=array_shift($args);
			return call_user_func_array(array($_obj,$_cmd),$args);
		} else {
			return $_obj->execute();
		}
		$this->output("Unknown command: {$func} called with args [".implode(' ',$args)."]\n");
		$this->help();
	}
	
	protected function getCommand($command){
		//$this->output($this->config[$command]);
		if(array_key_exists($command,$this->command)){
			if(is_object($this->command[$command])) return $this->command[$command];
			$_class='ss_cli_command_'.$command;
			$_obj=$this->command[$command]=new $_class($this->config[$command],$this->settngs);
			$_obj->setDispatch($this);
			return $_obj;
		}
		throw new BadMethodCallException();
	}
	
	public function __get($name){
		return $this->getCommand($name);
	}
	
	public function help(){
		$this->output("The following commands are available:\n");
		foreach($this->command as $_name=>$_obj){
			$this->output("{$_name}");
			//$_class='ss_cli_command_'.$name;
			//$class::help()
		}
		$this->output("\nTo learn more about a command type cli <command> help.");
	}
	
	public function output($data){
		if(is_array($data)||is_object($data)){
			print_r($data);
		} else {
			print($data."\n");
		}
	}
}
interface ss_cli_commandInterface{
	public function __construct($config,$ss);
}

class ss_cli_command{
	protected $config;
	protected $settings;
	public function __construct($config,$ss){
		$this->config=$config;
		$this->settings=$ss;
	}
	protected $dispatch;        /**     * Sets $command.     * @param object $command     * @see ss_cli_command::$command     */    public function setDispatch($dispatch)    {        $this->dispatch = $dispatch;    }
}
?>